import {Config} from "@/common/config";
import {getToken} from "@/utils/cache";
// @ts-ignore

/**
 * 检查是否完整路径.
 * 拼接.
 * @param url
 */
export const checkAndFixUrl = (url: string) :string => {
    // 判断是否包含 "http"
    if (!url || url.length <= 0) {
        return '';
    }
    // @ts-ignore
    if (!url.includes("http")) {
        // 如果不存在，则进行拼接
        url = Config.IME_HOST + '/' + url;
    }

    return url;
}

export const getServerStatic = (path: string) :string => {
    return Config.MINI_STATIC_HOST + path;
}

/**
 * 获取今天后6天的日期数据.
 */
export const getFutureDates = ():Array<any> => {
    const today = new Date();
    const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    const futureDates = [];

    for (let i = 0; i < 6; i++) {
        const currentDate = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
        const day = currentDate.getDate();
        const month = currentDate.getMonth() + 1; // Months are zero-based
        const year = currentDate.getFullYear();

        const formattedDate = `${month < 10 ? '0' : ''}${month}/${day < 10 ? '0' : ''}${day}`;
        const dayOfWeek = daysOfWeek[currentDate.getDay()];
        const fullDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;

        futureDates.push({
            date: formattedDate,
            desc: i === 0 ? '今天' : i === 1 ? '明天' : dayOfWeek,
            fullDate: fullDate,
        });
    }

    return futureDates;
}

/**
 * 获取对应日期的星期.
 * @param dateString
 */
export const getDayOfWeek = (dateString: string): string => {
    const date = new Date(dateString);
    const dayOfWeek = date.getDay();

    // 中文星期几表示数组
    const daysOfWeekChinese = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return daysOfWeekChinese[dayOfWeek];
}


/**
 * 防抖实现
 * 对于短时间内连续触发的事件（如滚动事件），防抖的含义就是让某个时间期限（如1000毫秒）内，事件处理函数只执行一次。
 * @param fn
 * @param delay
 * @returns {(function(): void)|*}
 */
export const debounce = (fn: () => Promise<void>, delay: number): any => {
    let timer = null //借助闭包
    return function() {
        if(timer){
            clearTimeout(timer)
        }
        timer = setTimeout(fn,delay) // 简化写法
    }
}


export const validateIDNumber = (idNumber: any) => {
    if (idNumber.length !== 18) {
        return false;
    }
    const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const verifyCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;
    for (let i = 0; i < 17; i++) {
        const digit = parseInt(idNumber.charAt(i));
        sum += digit * factors[i];
    }
    const remainder = sum % 11;
    const verifyCode = verifyCodes[remainder];
    return verifyCode === idNumber.charAt(17).toUpperCase();
}

export const getAge = (idNumber:any) => {
    var regex = /^[1-9][0-9]{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[0-9Xx]$/;
    if (!regex.test(idNumber)) {
        return 0;
        throw new Error("Invalid ID Number");
    }

    var birthday = idNumber.substr(6, 8);
    var year = birthday.substr(0, 4);
    var month = birthday.substr(4, 2);
    var day = birthday.substr(6, 2);

    var now = new Date();
    var age = now.getFullYear() - parseInt(year, 10);
    if (now.getMonth() + 1 < parseInt(month, 10) || (now.getMonth() + 1 === parseInt(month, 10) && now.getDate() < parseInt(day, 10))) {
        age--;
    }
    return age;
}
